package com.wwj.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/19.
 */
public class QRCodeUtil {
    /**
     * @param file      输出二维码文件路径
     * @param accessUrl 二维码的文字内容
     * @param width     二维码的宽度
     * @param height    二维码的高度
     * @param format    二维码文件格式：png/jpeg/gif/bmp/
     */
    public static void encoderQRCode(String file, String accessUrl, int width, int height, String format) throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(accessUrl, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
        Path path = FileSystems.getDefault().getPath(file);
        MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
    }

    /**
     * @param stream    输出流
     * @param accessUrl 二维码的文字内容
     * @param width     二维码的宽度
     * @param height    二维码的高度
     * @param format    二维码文件格式：png/jpeg/gif/bmp/
     */
    public static void encoderQRCode(OutputStream stream, String accessUrl, int width, int height, String format) throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(accessUrl, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
        MatrixToImageWriter.writeToStream(bitMatrix, format, stream);
    }

    /**
     * 去白边
     * @param matrix
     * @return
     */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 0;
        int resHeight = rec[3] + 0;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

    public static void main(String[] args) throws Exception {
        encoderQRCode("d:/b.png", "http://www.baidu.com", 400, 400, "png");
    }
}
